package com.airnewslinkosky.ticket.ui.client;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.PassengerInfo;
import com.airnewslinkosky.ticket.model.PassengerInfoResult;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.pay.util.BaseHelper;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.util.CheckCetiType;
import com.airnewslinkosky.ticket.util.Constants;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.mobclick.android.MobclickAgent;

public class ClientContactsAdd  extends BaseActivity implements OnClickListener{
	public  final int DIALOG_IDTYPE_LIST = 10;
	public  final int DATE_DIALOG_ID = 9;
	//证件类型,生日
	private TextView cardType,birthday;
	private RelativeLayout cardTypeLayout,birthdayLay;
	
	private int mYear;
    private int mMonth;
    private int mDay;
    
	private EditText userName,cardNo,mobile,email,remark,address;
	
	private SharedPreferences sp;
	private Toast toast;
	
	private ProgressDialog progressDialog = null;
	public Handler myHandler;
	public final int SUCCESS = 0;
	public final int USER_ERROR = 1;
    
	public static PassengerInfo passengerInfo;
	
	public static String customerNo = "";
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client_contact);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
        
		activityList.add(this);
		System.out.println("customerNo="+customerNo);
		rendData();	
		setData();
		
		//得到当前日期
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        
        cardTypeLayout.setOnClickListener(this);
		birthdayLay.setOnClickListener(this);
		
		findViewById(R.id.backBut).setOnClickListener(this);
		findViewById(R.id.clientContactButton).setOnClickListener(this);
		
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case SUCCESS :
					toast = Toast.makeText(ClientContactsAdd.this, "成功保存常旅客信息", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
//					new Thread(new Runnable() {
//						public void run() {
//							try {
//								Thread.sleep(5000);
//							} catch (final InterruptedException e) {
//								e.printStackTrace();
//							}
//						}
//					});
					Intent intentR = new Intent();
					intentR.setClass(ClientContactsAdd.this, ClientContactsList.class);
					ClientContactsList.isSearch = true;
					startActivity(intentR);
					break;
				case USER_ERROR:
					BaseHelper.showDialog(ClientContactsAdd.this, "提示", (String)msg.obj,R.drawable.infoicon);
					break;
				}
			}
		};
	}
	
	private void rendData() {
		cardTypeLayout = (RelativeLayout)findViewById(R.id.cardTypeLayout);
		cardType =  (TextView)findViewById(R.id.cardType);
		
		birthdayLay = (RelativeLayout)findViewById(R.id.birthdayLay);
		birthday =  (TextView)findViewById(R.id.birthday);
		
		userName = (EditText)findViewById(R.id.userName);
		cardNo = (EditText)findViewById(R.id.cardNo);
		mobile = (EditText)findViewById(R.id.mobile);
		email = (EditText)findViewById(R.id.email);
		remark = (EditText)findViewById(R.id.remark);
		address = (EditText)findViewById(R.id.address);
	}
	
	private void setData() {
		if(passengerInfo != null){
			userName.setText(passengerInfo.PassengerName);
			cardNo.setText(passengerInfo.IDNo);
			mobile.setText(passengerInfo.PassengerMobile);
			birthday.setText(passengerInfo.Birthday);
			cardType.setText(FlyUtil.getCardLabel(Integer.valueOf(passengerInfo.IDType)));
			email.setText(passengerInfo.Email);
			remark.setText(passengerInfo.Remark);
		}
	}
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.clientContactButton:
			if ("".equals(userName.getText().toString()) || "".equals(cardType.getText().toString()) || "".equals(cardNo.getText().toString()) || "".equals(mobile.getText().toString()) ||  "".equals(email.getText().toString())){
				BaseHelper.showDialog(ClientContactsAdd.this, "提示", "请填写完整信息",R.drawable.infoicon);
				return;
			}
			if (!mobile.getText().toString().matches("[0-9]{11}")) {
				toast = Toast.makeText(ClientContactsAdd.this, "手机号填写不正确", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;
			}
			if (!email.getText().toString().matches("\\w+@(\\w+\\.)+[a-z]{2,3}")) {
				toast = Toast.makeText(ClientContactsAdd.this, "Email填写不正确", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;
			}
			String birthdayValue = "";
			if("身份证".equals(cardType.getText().toString())){
				birthdayValue = CheckCetiType.getCertiCodeToBirtday(cardNo.getText().toString());
			} else {
				birthdayValue =  birthday.getText().toString();
			}
			
			PassengerInfo passengerInfoNew = new PassengerInfo();
			
			String operateType = "INSERT";
			if(passengerInfo != null){
				operateType = "UPDATE";
				passengerInfoNew.PassengerNo = String.valueOf(passengerInfo.PassengerNo);//乘客编号
				System.out.println("passengerInfo.PassengerNo="+passengerInfo.PassengerNo);
				System.out.println("passengerInfo.Email="+passengerInfo.Email);
			}
			
			passengerInfoNew.CustomerNo = customerNo;
			passengerInfoNew.PassengerName = String.valueOf(userName.getText());//乘客姓名
			passengerInfoNew.PassengerType = String.valueOf("0");//乘客种类
			passengerInfoNew.IDType = String.valueOf(FlyUtil.getCardPosition(String.valueOf(cardType.getText())));//证件类型默认为0身份证
			passengerInfoNew.IDNo = String.valueOf(cardNo.getText());//证件号码
			passengerInfoNew.Birthday = birthdayValue;//出生日期
			passengerInfoNew.PassengerMobile = String.valueOf(mobile.getText());//乘客手机号码
			passengerInfoNew.PassengerLevel = String.valueOf("1");//乘客级别
			passengerInfoNew.PassengerState = String.valueOf("1");//乘客状态
			passengerInfoNew.Remark = String.valueOf(remark.getText());
			passengerInfoNew.Email = String.valueOf(email.getText());
			
			List<PassengerInfo> passengerInfoList = new ArrayList<PassengerInfo>();
			passengerInfoList.add(passengerInfoNew);
			save(passengerInfoList,operateType);
			break;
		case R.id.backBut: 
			Intent intentR = new Intent();
			intentR.setClass(ClientContactsAdd.this, ClientContactsList.class);
			ClientContactsList.isSearch = true;
			startActivity(intentR);
			break;
		case R.id.cardTypeLayout:
			showDialog(DIALOG_IDTYPE_LIST);
			break;
		case R.id.birthdayLay:
			showDialog(DATE_DIALOG_ID);
			break;
		}
	}

	private void save(final List<PassengerInfo> passengerInfoList,final String operateType) {
		progressDialog = ProgressDialog.show(ClientContactsAdd.this, "请稍等...", "保存常旅客可能会\n占用比较长时间...",true);
		final Thread thread = new Thread() {
			public void run() {
//				sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
//		        String userIdLogin = sp.getString("userIdB2B", null);
//		        String userPwd =  sp.getString("userPwdB2B", null);
//		        String asToken =   sp.getString("ASTokenB2B", null);
		        
		        String userIdLogin = Constants.USERID;
		        String userPwd =  Constants.USERPWD;
		        String asToken =  Constants.ASToken;
		        
		        PassengerInfoResult passengerInfoResult = WebAccessor.passengerInfoManage(userIdLogin,userPwd,asToken,operateType,passengerInfoList);
		        
		        if(passengerInfoResult.Result.equals("0")) {
		        	Message msg = new Message();
					msg.what = SUCCESS;
					myHandler.sendMessage(msg);
					progressDialog.dismiss();
					return;
		        } else {
		        	Message msg = new Message();
					msg.what = USER_ERROR;
					msg.obj = passengerInfoResult.ErrorDescription;
					myHandler.sendMessage(msg);
					progressDialog.dismiss();
					return;
		        }
			}
		};
		thread.start();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		    case DIALOG_IDTYPE_LIST:
	            return new AlertDialog.Builder(ClientContactsAdd.this)
	                .setIcon(R.drawable.ic_menu_more)
	                .setTitle("请选择")
	                .setSingleChoiceItems(R.array.paperTypes, 0, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	String[] arrs = getResources().getStringArray(R.array.paperTypes);
	                    	cardType.setText(arrs[whichButton]);
	                    	if(!arrs[whichButton].equals("身份证")){
	                    		birthdayLay.setVisibility(View.VISIBLE);
	                    	} else {
	                    		birthdayLay.setVisibility(View.GONE);
	                    	}
	                    	dialog.dismiss();
	                        /* User clicked on a radio button do some stuff */
	                    }
	                })
	                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    
	                    }
	                })
	                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    }
	                })
	               .create();
		    case DATE_DIALOG_ID:
		    	return new DatePickerDialog(this, dsl, mYear, mMonth, mDay);
		    default:
				return null;
		}
	}
	
    //准备日期设置监听器
    private OnDateSetListener dsl = new DatePickerDialog.OnDateSetListener(){

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear =year;
			mMonth= monthOfYear;
			mDay= dayOfMonth;
			birthday.setText(mYear+"-"+(mMonth+1)+"-"+mDay);
		}
    };
    
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
